/* eslint-disable */

import Cookies from 'js-cookie'
import Vue from 'vue'

let COOKIE_DATA = {
  user: getUserInfo(),
  header: getRequestHeader()
}

// 存储pending 状态请求
export const pendingRequest = new Map()

// 存储 message
export const messageWrap = {
  message: null
}

/**
 * 获取请求头中 cookie 数据
 */
export function getRequestHeader () {
  return {
    Authorization: Cookies.get('BEARER_TOKEN'),
    'W-FLOW': Cookies.get('W-FLOW') || 'default',
    'W-SEQ': Cookies.get('W-SEQ') || '1569595974015_2',
    'X-DEBUG': Cookies.get('X-DEBUG') || null,
    'W-EVENT': Cookies.get('W-EVENT') || null,
    'X-LOGGER-EVENT': Cookies.get('X-LOGGER-EVENT') || '',
    'X-LOGGER': Cookies.get('X-LOGGER') || '',
    ip: Cookies.get('ip') || 'http://127.0.0.1'
  }
}

/**
 * 获取cookie 中 userInfo 信息
 */
export function getUserInfo () {
  let userInfo = Cookies.get('userInfo')
  try {
    userInfo = userInfo ? JSON.parse(userInfo) : {}
  } catch (e) {
    userInfo = {}
    console.log(e)
  }
  return userInfo
}

// 获取cookie 数据
export function getCookieData () {
  return COOKIE_DATA
}

/**
 * 刷新请求头信息
 */
export function refreshCookieData () {
  // 判断重新登陆情况下重新获取, W-EVENT 或者 X-LOGGER-EVENT 改变 自动重新获取 W-EVENT
  const BEARER_TOKEN = Cookies.get('BEARER_TOKEN')
  const W_EVENT = Cookies.get('W-EVENT')
  const X_LOGGER_EVENT = Cookies.get('X-LOGGER-EVENT')
  if ( BEARER_TOKEN !== COOKIE_DATA.header.Authorization ||
      (W_EVENT && W_EVENT !== COOKIE_DATA.header['W-EVENT']) ||
      (X_LOGGER_EVENT && X_LOGGER_EVENT !== COOKIE_DATA.header['X-LOGGER-EVENT'])) {
    COOKIE_DATA = {
      user: getUserInfo() || {},
      header: getRequestHeader()
    }
  }
  return COOKIE_DATA
}

/**
 * 清除所有pending状态的请求
 * @param {Array} whileList 白名单，里面的请求不会被取消
 */
export function clearPendingRequest (whiteList = []) {
  if (!pendingRequest.size) return
  const pendingUrlList = Array.from(pendingRequest.keys()).filter((url) => {
    const cancelList = whiteList.find(whiteUrl => {
      return url.indexOf(whiteUrl) !== -1
    })
    return !cancelList || !cancelList.length
  })
  if (!pendingUrlList.length) return
  pendingUrlList.forEach((pendingUrl) => {
    // 清除掉所有非全局的pending状态下的请求
    if (!pendingRequest.get(pendingUrl).global) {
      pendingRequest.get(pendingUrl).cancelFn('')
      pendingRequest.delete(pendingUrl)
    }
  })
  return pendingUrlList
}

/**
 *
 * @param {Function} message 消息弹窗方法
 * @param {Object} err 错误信息对象
 * @param {String} err.message 错误提示信息
 * @param {Object} options 消息弹窗配置对象
 * @param {Boolean} options.showDetail 是否展示错误详情
 * @param {Boolean} options.showClose 是否展示关闭按钮
 */
export const showErrMessage = (message, err, options = {}) => {
  if (!err) return
  if (!message) {
    console.warn('无 Message 方法, 请在request实例化时传入Message')
    return
  }
  const { detailMsg } = err
  message({
    message: err.message || options.failTxt,
    type: err.type || 'error',
    showDetail: options.showDetail !== false,
    errorUrl: err.path || null,
    detailMsg: detailMsg || null,
    traceid: err.id || null,
    // showClose: options.showClose !== false,
    duration: options.duration || 5000
  })
}

export const showSuccessMessage = (message, options) => {
  if (!message) {
    console.warn('无 Message 方法, 请在request实例化时传入Message')
    return
  }
  message({
    message: options.successTxt,
    type: 'success',
    // showClose: options.showClose === true,
    duration: options.duration || 5000
  })
}

export const handleError = (err) => {
  if (err.stack && err.stack.includes('timeout')) {
    err.message = '请求超时!'
  }
  const { response } = err
  if (!response) return err
  if (!response.status) {
    err.code = ''
    err.message = '未知错误：有response但没有response.status'
  }

  switch (response.status) {
    case 400:
      err.message = '请求错误（400）'
      break
    case 401:
      err.message = '未授权，请重新登录(401)'
      break
    case 403:
      err.message = '拒绝访问(403)'
      break
    case 404:
      err.message = '请求出错(404)'
      break
    case 408:
      err.message = '请求超时(408)'
      break
    case 500:
      err.message = '服务器错误(500)'
      break
    case 501:
      err.message = '服务未实现(501)'
      break
    case 502:
      err.message = '网络错误(502)'
      break
    case 503:
      err.message = '服务不可用(503)'
      break
    case 504:
      err.message = '网络超时(504)'
      break
    default:
      err.message = `连接出错，状态码：(${err.response.status})!`
  }
  return err
}

/**
 * 找默认Message 方法
 */
export function findDefaultMessage () {
  const V = Vue || window.Vue
  let Message = messageWrap.message
  if (!Message && V) {
    Message = V.prototype.$messageEx ? V.prototype.$messageEx : V.prototype.$message
  }
  return Message
}
